package com.erp.freight.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.erp.freight.domain.KjxStoreAccount;
import com.erp.freight.domain.bo.KjxStoreProductRecordBo;
import com.erp.freight.domain.kjx.InventoryRequest;
import com.erp.freight.domain.kjx.KjxReplenishment;
import com.erp.freight.domain.kjx.KjxStockProduct;
import com.erp.freight.domain.kjx.KjxStoreQueryParam;
import com.erp.freight.domain.vo.KjxStoreProductRecordVo;
import com.erp.freight.service.IKjxStoreAccountService;
import com.erp.freight.service.IKjxStoreProductRecordService;
import com.erp.freight.service.KjxLogisticsService;
import com.ruoyi.common.core.annotation.RepeatSubmit;
import com.ruoyi.common.core.domain.PageQuery;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.web.oldController.BaseController;
import com.ruoyi.common.core.web.oldPage.TableDataInfo;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.gather.api.RemoteCollectProductSkuService;
import com.ruoyi.gather.api.domain.ErpCollectProductSku;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import java.math.BigDecimal;
import java.util.*;

/**
 * 熊迪库存记录
 *
 * @author erp
 * @date 2024-04-07
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/kjx/storeProductRecord")
public class KjxStoreProductRecordController extends BaseController {

    private final IKjxStoreProductRecordService iKjxStoreProductRecordService;
    private final KjxLogisticsService kjxLogisticsService;
    private final IKjxStoreAccountService storeAccountService;
    private final RemoteCollectProductSkuService remoteCollectProductSkuService;

    /**
     * 库存申请
     */
    @PostMapping("/inventoryRequest")
    public R<Object> inventoryRequest(@RequestBody InventoryRequest request) {
        // 获取token
        KjxStoreAccount infoByAccount = storeAccountService.getInfoByAccount(request.getUserName());
        String token = infoByAccount.getToken();
        request.setToken(token);
        // 获取sku图片
        ErpCollectProductSku collectProductSku = remoteCollectProductSkuService.getSkuInfoBySkuCode(request.getAnotherName());
        if (collectProductSku != null) {
            String skuImage = collectProductSku.getSkuImage();
            if (skuImage.startsWith("http")) {
                request.setSkuImage(skuImage);
            }else {
                request.setSkuImage("https://file.pbb2c.com/" + skuImage);
            }
        }
        String desp = "";
        if (StringUtils.isNotEmpty(request.getDesp())) {
            desp = "快递单号：" + request.getTrackingNo() +"，  " + request.getDesp();
        }else {
            desp = "快递单号：" + request.getTrackingNo();
        }
        request.setDesp(desp);
        // 库存申请
        kjxLogisticsService.inventoryRequest(request);
        // 保存记录
        KjxStoreProductRecordBo record = new KjxStoreProductRecordBo();
        String userName = request.getUserName();
        record.setAccount(userName);
        record.setPrice(new BigDecimal(request.getPurchasePrice()));
        record.setCount(request.getSkuNum());
        record.setProof(request.getProof());
        record.setAddTime(new Date());
        record.setWaybillNumber(request.getTrackingNo());
        record.setWarehouseId(request.getStockPlusDeliveryId());
        record.setType(0);
        iKjxStoreProductRecordService.insertByBo(record);
        
        return R.ok();
    }

    /**
     * 补仓
     */
    @PostMapping("/replenishment")
    public void replenishment(@RequestBody KjxReplenishment replenishment) {
        // 获取token
        KjxStoreAccount infoByAccount = storeAccountService.getInfoByAccount(replenishment.getUserName());
        String token = infoByAccount.getToken();
        replenishment.setToken(token);
        kjxLogisticsService.replenishment(replenishment);
        // 保存记录
        KjxStoreProductRecordBo record = new KjxStoreProductRecordBo();
        String userName = replenishment.getUserName();
        record.setAccount(userName);
        record.setPrice(replenishment.getPurchasePrice());
        record.setProof(replenishment.getProof());
        record.setCount(replenishment.getCpfrAmount());
        record.setAddTime(new Date());
        record.setWaybillNumber(replenishment.getTrackingNo());
        record.setWarehouseId(replenishment.getStockPlusDeliveryId());
        record.setType(2);
        iKjxStoreProductRecordService.insertByBo(record);
    }

    /**
     * 获取仓库地址列表
     */
    @GetMapping("/getStoreAddress")
    public R<Object> getStoreAddress(String account) {
        String addrStr = kjxLogisticsService.rechargeAndAdditionalServiceList(account);
        JSONObject jsonObject = JSONObject.parseObject(addrStr);
        Map<String, Object> map = new HashMap<>();
        List<Object> list = new ArrayList<>();
        JSONArray data = jsonObject.getJSONArray("data");
        for (int i = 0; i < data.size(); i++) {
            map = new HashMap<>();
            JSONObject jsonData = data.getJSONObject(i);
            Integer storeAddressId = jsonData.getInteger("storeAddressId");
            map.put("storeAddressId", storeAddressId);
            String storeName = jsonData.getString("storeName");
            map.put("storeName", storeName);
            Integer storeId = jsonData.getInteger("storeId");
            map.put("storeId", storeId);
            list.add(map);
        }
        return R.ok(list);
    }

    /**
     * 获取所有仓库列表
     */
    @GetMapping("/getKjxStoreInfo")
    public R<Object> getKjxStoreInfo() {
        String kjxStoreInfo = kjxLogisticsService.getKjxStoreInfo();
        return R.ok(kjxStoreInfo);
    }

    @GetMapping("/storeProductList")
    public R<Object> storeProductList(KjxStoreQueryParam param) {
        Page<KjxStockProduct> list = kjxLogisticsService.storeProductList(param);
        TableDataInfo<KjxStockProduct> info = TableDataInfo.build(list);
        return R.ok(info);
    }

    /**
     * 查询熊迪库存记录列表
     */
    @GetMapping("/list")
    public TableDataInfo<KjxStoreProductRecordVo> list(KjxStoreProductRecordBo bo, PageQuery pageQuery) {
        return iKjxStoreProductRecordService.queryPageList(bo, pageQuery);
    }

    /**
     * 导出熊迪库存记录列表
     */
    @Log(title = "熊迪库存记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(KjxStoreProductRecordBo bo, HttpServletResponse response) {
        List<KjxStoreProductRecordVo> list = iKjxStoreProductRecordService.queryList(bo);
    }

    /**
     * 获取熊迪库存记录详细信息
     *
     * @param id 主键
     */
    @GetMapping("/{id}")
    public R<KjxStoreProductRecordVo> getInfo(@NotNull(message = "主键不能为空")
                                     @PathVariable Long id) {
        return R.ok(iKjxStoreProductRecordService.queryById(id));
    }

    /**
     * 新增熊迪库存记录
     */
    @Log(title = "熊迪库存记录", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@RequestBody KjxStoreProductRecordBo bo) {
        return toAjax(iKjxStoreProductRecordService.insertByBo(bo));
    }

    /**
     * 修改熊迪库存记录
     */
    @Log(title = "熊迪库存记录", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@RequestBody KjxStoreProductRecordBo bo) {
        return toAjax(iKjxStoreProductRecordService.updateByBo(bo));
    }

    /**
     * 删除熊迪库存记录
     *
     * @param ids 主键串
     */
    @Log(title = "熊迪库存记录", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] ids) {
        return toAjax(iKjxStoreProductRecordService.deleteWithValidByIds(Arrays.asList(ids), true));
    }
}
